package org.zyj.io.protocal.custom;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.zyj.io.protocal.Message;

/**
 * 此代码没考虑粘包半包问题, 但不影响我们学习pipeline中数据流转的规则
 */
public class MessageDecoder extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf receiveBuf = (ByteBuf) msg;
        int length = receiveBuf.readInt();
        int version = receiveBuf.readInt();
        int opCode = receiveBuf.readInt();
        int streamId = receiveBuf.readInt();
        byte[] body = new byte[length];
        for (int i = 0; i < length; i++) {
            if (receiveBuf.isReadable()){
                body[i] = receiveBuf.readByte();
            }else {
                break;
            }
        }
        //组装message对象
        Message message = new Message();
        message.setVersion(version);
        message.setOpCode(opCode);
        message.setStreamId(streamId);
        message.setBody(body);
        ctx.fireChannelRead(message);
    }
}
